// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.search.ui

import android.content.Context
import android.content.Intent
import android.graphics.CornerPathEffect
import android.graphics.Paint
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import dev.bandb.graphview.AbstractGraphAdapter
import dev.bandb.graphview.layouts.layered.SugiyamaArrowEdgeDecoration
import dev.bandb.graphview.layouts.layered.SugiyamaConfiguration
import dev.bandb.graphview.layouts.layered.SugiyamaLayoutManager
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.databinding.FragmentLineGraphBinding
import xyz.apiote.bimba.czwek.departures.DeparturesActivity
import xyz.apiote.bimba.czwek.repo.Colour
import xyz.apiote.bimba.czwek.repo.LineGraph
import xyz.apiote.bimba.czwek.repo.StopStub
import xyz.apiote.bimba.czwek.search.ui.results.BimbaViewHolder


class LineGraphFragment : Fragment() {

	private lateinit var pageViewModel: PageViewModel
	private var _binding: FragmentLineGraphBinding? = null
	private val binding get() = _binding!!
	private lateinit var adapter: LineGraphAdapter

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		adapter = LineGraphAdapter(
			arguments?.getString("lineID", "") ?: "",
			arguments?.getString("lineName", "") ?: "",
			arguments?.getString("feedID", "") ?: ""
		)
		pageViewModel = ViewModelProvider(this)[PageViewModel::class.java].apply {
		}
	}

	override fun onCreateView(
		inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
	): View {

		_binding = FragmentLineGraphBinding.inflate(inflater, container, false)

		ViewCompat.setOnApplyWindowInsetsListener(binding.recycler) { v, windowInsets ->
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			v.updatePadding(
				right = insets.right,
				left = insets.left,
				top = insets.top,
				bottom = insets.bottom
			)
			windowInsets
		}

		val configuration = SugiyamaConfiguration.Builder()
			.setLevelSeparation(100)
			.build()

		binding.recycler.layoutManager = SugiyamaLayoutManager(requireContext(), configuration)
		binding.recycler.addItemDecoration(SugiyamaArrowEdgeDecoration(Paint(Paint.ANTI_ALIAS_FLAG).apply {
			strokeWidth = 5f
			color = context?.let {
				Colour.getThemeColour(com.google.android.material.R.attr.colorOnBackground, it)
			} ?: 0
			style = Paint.Style.STROKE
			strokeJoin = Paint.Join.ROUND
			pathEffect = CornerPathEffect(10f)
		}))
		binding.recycler.adapter = adapter
		pageViewModel.let {
			val lineGraph = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
				arguments?.getParcelable("graph", LineGraph::class.java)
			} else {
				@Suppress("DEPRECATION")
				arguments?.getParcelable("graph") as LineGraph?
			}
			it.setupGraphView(lineGraph!!)
			it.data.observe(viewLifecycleOwner) { graph ->
				adapter.submitGraph(graph)
			}
		}

		return binding.root
	}

	companion object {
		@JvmStatic
		fun newInstance(
			lineGraph: LineGraph,
			lineID: String,
			lineName: String,
			feedID: String
		): LineGraphFragment {
			return LineGraphFragment().apply {
				arguments = Bundle().apply {
					putParcelable("graph", lineGraph)
					putString("lineID", lineID)
					putString("lineName", lineName)
					putString("feedID", feedID)
				}
			}
		}
	}

	override fun onDestroyView() {
		super.onDestroyView()
		_binding = null
	}
}

class LineGraphAdapter(
	private val lineID: String,
	private val lineName: String,
	private val feedID: String
) :
	AbstractGraphAdapter<BimbaViewHolder>() {
	private lateinit var context: Context
	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BimbaViewHolder {
		context = parent.context
		val view = LayoutInflater.from(parent.context)
			.inflate(R.layout.result, parent, false)
		return BimbaViewHolder(view)
	}

	override fun onBindViewHolder(holder: BimbaViewHolder, position: Int) {
		BimbaViewHolder.bind(getNodeData(position) as StopStub, holder, context) {
			val intent = Intent(context, DeparturesActivity::class.java).apply {
				putExtra("code", it.code)
				putExtra("name", it.name)
				putExtra("line", lineName)
				putExtra("lineID", lineID)
				putExtra("feedID", feedID)
			}
			context.startActivity(intent)
		}
	}
}
